﻿using DevExpress.XtraEditors;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using pTools.ChildWin;
using pTools.cMethods;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;

namespace pTools
{
    /// <summary>
    /// 生产计划打码
    /// </summary>
    public partial class PlanBarPrint : DevExpress.XtraEditors.XtraForm
    {
        Dictionary<string, string> pars;
        DBHelper db;
        HttpAgreement http;
        public PlanBarPrint(Dictionary<string, string> dic)
        {
            InitializeComponent();
            db = new DBHelper();
            http = new HttpAgreement();
            pars = dic;

        }

        private void PlanBarPrint_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = "条码打印";
                //this.WindowState = FormWindowState.Maximized;
                CommonMethods.PlanInfoSetForm(pars, this.gcBar.Controls, false);
                this.SetCommonPars(pars);
                CommonMethods.loadPrintTemplte(cb_0_Template);

                CommonMethods.loadPrintDevice(cb_0_Print);
                //tb_0_spec.Text = pars["spec"];
                tb_0_printCount.Text = "1";
                tb_1_printNum.Text = "1";
                tbQuPi.Text = "0";

                LoadProduceGroup();

                //LoadLengthAndWidth();

                LoadSingleWeight();

                //openCOMPort();

                //StartCOM();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        void LoadSingleWeight()
        {
            var json = JsonConvert.DeserializeObject<JObject>(pars["pars"]);

            var plCode = json["plCode"];
            var proCode = json["proCode"];

            var sql = "select * from pi_ProductionPlan_products where plCode = '" + plCode + "' and proCode = '" + proCode + "' ";
            var dt = db.getData(sql, "");

            var singleWeight = dt.Rows[0]["cu_singleWeight"].ToString();

            tb_0_cu_singleWeight.Text = singleWeight;
        }

        SerialPort port;
        void StartCOM()
        {

            var com = ConfigurationSettings.AppSettings["PortName"]; //COM1
            var baudrate = Convert.ToInt32(ConfigurationSettings.AppSettings["BautRate"]);
            port = new SerialPort(com, baudrate);

            port.DataBits = 8;
            port.StopBits = StopBits.One;

            port.DataReceived += port_DataReceived;

            try
            {
                if (port.IsOpen)
                {
                    port.Close();
                    port.Open();
                }
                else
                {
                    port.Open();
                }
            }
            catch (Exception ex)
            {

                MessageBox.Show("串口打开失败!" + ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        string pool = "";
        void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int len = port.BytesToRead;
            byte[] readBuffer = new byte[len];
            port.Read(readBuffer, 0, len);

            var receivedStr = Encoding.ASCII.GetString(readBuffer, 0, len);

            pool += receivedStr;
            //+000012018

            if (pool.Length < 20)
            {
                return;
            }

            var startIndex = -1;

            if (pool.IndexOf("+") > 0)
            {
                startIndex = pool.IndexOf('+');
            }
            else if (pool.IndexOf("-") > 0)
            {
                startIndex = pool.IndexOf('-');
            }
            else
            {
                return;
            }

            if (pool.Length - startIndex < 8)
            {
                return;
            }

            var readingStr = pool.Substring(startIndex, 7);

            var value = decimal.Parse(readingStr);
            var valueStr = value.ToString();

            tbMaoZhong
            .Invoke((MethodInvoker)delegate
            {
                tbMaoZhong.Text = valueStr;
            });

            pool = "";
        }

        private void LoadLengthAndWidth()
        {
            var json = JsonConvert.DeserializeObject<JObject>(pars["pars"]);

            var proCode = json["proCode"];
            var plCode = json["plCode"];

            var sql = "select * from pi_ProductionPlan_products where proCode = '" + proCode + "' and plCode = '" + plCode + "'";
            var dt = db.getData(sql, "");

            var width = dt.Rows[0]["cu_widthRange"].ToString();
            var length = dt.Rows[0]["cu_rollLength"].ToString();

            tb_1_cu_widthRange.EditValue = width;
            tb_1_cu_rollLength.EditValue = length;

            tb_1_cu_widthRange.Enabled = true;
            tb_1_cu_rollLength.Enabled = true;

        }

        private decimal LoadPieceOfNum()
        {
            var json = JsonConvert.DeserializeObject<JObject>(pars["pars"]);

            var proCode = json["proCode"];
            var plCode = json["plCode"];

            var sql = "select * from pi_ProductionPlan_products where proCode = '" + proCode + "' and plCode = '" + plCode + "'";
            var dt = db.getData(sql, "");

            var pieceStr = dt.Rows[0]["cu_numberOfPieces"].ToString();
            if (!string.IsNullOrEmpty(pieceStr))
            {
                return decimal.Parse(pieceStr);
            }
            else
            {
                return 0.0m;
            }
        }

        // 加载生产班组
        private void LoadProduceGroup()
        {
            var sql = "select ccode,cname from fun_CommonData_Info where cType = 'PROGROUP' and cCode <> ''";
            var dt = db.getData(sql, "");

            cb_0_cu_workGroup.DataSource = dt;
            cb_0_cu_workGroup.DisplayMember = "cname";
            cb_0_cu_workGroup.ValueMember = "ccode";
        }

        Dictionary<string, string> cmPars = new Dictionary<string, string>();
        /// <summary>
        /// 设置通用参数
        /// </summary>
        /// <param name="pars"></param>
        private void SetCommonPars(Dictionary<string, string> pars)
        {
            var json = JsonConvert.DeserializeObject<JObject>(pars["pars"]);
            cmPars["gxCode"] = json["gxCode"].ToString();
            cmPars["unit"] = json["unit"].ToString();
            cmPars["dataId"] = json["id"].ToString();
            cmPars["isInitial"] = "N";
            cmPars["machine"] = json["machine"].ToString();
            cmPars["planType"] = json["plType"].ToString();
        }

        private void AlterTable(DataTable dt)
        {
            // 添加阻燃字段
            dt.Columns.Add("cu_flameRetardant");
            // 添加色号
            dt.Columns.Add("cu_colorCode");
            // 添加压纹
            dt.Columns.Add("cu_texture");
            // 添加条码序号
            dt.Columns.Add("cu_productIndex");
            // 添加毛重
            dt.Columns.Add("cu_grossWeight");
            // 添加打印日期
            dt.Columns.Add("createtime");
            // 添加PHR
            dt.Columns.Add("cu_PHR");

            // 添加自定义克重 非U8
            dt.Columns.Add("cu_gramWeight");

            // 添加软硬度
            dt.Columns.Add("cu_hardnessDegree");

            // 添加面底
            dt.Columns.Add("cu_faceBottom");


            var json = JsonConvert.DeserializeObject<JObject>(pars["pars"]);

            var proCode = json["proCode"];
            var plCode = json["plCode"];

            var sql = "select * from pi_ProductionPlan_products where proCode = '" + proCode + "' and plCode = '" + plCode + "'";
            var resultTable = db.getData(sql, "");

            foreach (DataRow row in dt.Rows)
            {
                row["cu_flameRetardant"] = resultTable.Rows[0]["cu_flameRetardant"];
                row["cu_colorCode"] = resultTable.Rows[0]["cu_colorCode"];
                row["cu_texture"] = resultTable.Rows[0]["cu_texture"];
                row["cu_PHR"] = resultTable.Rows[0]["cu_PHR"];
                row["cu_gramWeight"] = resultTable.Rows[0]["cu_gramWeight"];

                var bSql = "select cu_productIndex,cu_grossWeight,createtime from bar_productbarcode_info where barcode = '" + row["barCode"].ToString() + "' ";
                var bDt = db.getData(bSql, "");
                row["cu_productIndex"] = bDt.Rows[0]["cu_productIndex"];
                // 返回条码库中取，而不是直接取界面，是因为界面连电子秤，可能有数据突变
                row["cu_grossWeight"] = bDt.Rows[0]["cu_grossWeight"];
                row["createtime"] = bDt.Rows[0]["createtime"];
                row["cu_hardnessDegree"] = resultTable.Rows[0]["cu_hardnessDegree"];

                row["spec"] = tb_1_cu_rollLength.Text + " * " + tb_1_cu_widthRange.Text;
                row["cu_faceBottom"] = resultTable.Rows[0]["cu_faceBottom"];
            }
        }

        private void btnPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                var datas = CommonMethods.GetFormData(this.gcBar.Controls, cmPars);
                if (datas == null)
                {
                    MessageBox.Show("参数获取异常", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                datas["userCodes"] = CommonMethods.selectUserCodes;
                datas["barStatus"] = "need-in";//后期需要改为根据配置进行修改
                datas["createuser"] = CommonMethods.userCode;

                //打印条码取值
                //根据存货计量单位判断

                //计量单位：公斤
                //取值：电子秤读数

                //计量单位：平方米
                //取值：宽幅*卷长

                //计量单位：米
                //取值：卷长*生产计划中件数
                if (tb_0_unitName.Text == "公斤")
                {
                    datas["unit"] = "kg";
                    datas["number"] = tb_1_proWeight.Text;
                }
                else if (tb_0_unitName.Text == "平方米")
                {
                    datas["unit"] = "pingmi";
                    var lenStr = tb_1_cu_rollLength.Text;
                    var lenValue = 0.0m;
                    decimal.TryParse(lenStr, out lenValue);

                    var widStr = tb_1_cu_widthRange.Text;
                    var widValue = 0.0m;
                    decimal.TryParse(widStr, out widValue);

                    datas["number"] = (lenValue * widValue).ToString("0.00");
                }
                else if (tb_0_unitName.Text == "米数")
                {
                    datas["unit"] = "meter";
                    var pieceOfNum = LoadPieceOfNum();
                    datas["number"] = (decimal.Parse(tb_1_cu_rollLength.Text) * pieceOfNum).ToString("0.00");
                }
                else
                {
                    datas["number"] = "0";
                }

                datas["proGroup"] = cb_0_cu_workGroup.SelectedValue.ToString();
                datas["cu_grossWeight"] = string.IsNullOrEmpty(tbMaoZhong.Text) ? "0" : tbMaoZhong.Text;
                datas["printCount"] = tb_0_printCount.Text;
                var msg = http.PostJson("SaveBarCode", JsonConvert.SerializeObject(datas));
                if (!string.IsNullOrWhiteSpace(msg))
                {
                    var json = JsonConvert.DeserializeObject<JObject>(msg);
                    if (bool.Parse(json["Result"].ToString()))
                    {
                        if (string.IsNullOrWhiteSpace(json["Data"].ToString()))
                        {
                            MessageBox.Show("接口返回数据异常，请联系开发人员", "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                            return;
                        }
                        #region 打印代码
                        var bars = json["Data"].ToString();
                        var table = CommonMethods.createPrintTable(this.gcBar.Controls, cmPars, bars);

                        AlterTable(table);

                        string info = "";
                        var pResult = CommonMethods.DoPrint(table, cb_0_Template.Text, cb_0_Print.Text, ref info);
                        if (!pResult)
                        {
                            MessageBox.Show(msg, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        }
                        //DoneBarCodes();
                        #endregion
                    }

                    else
                    {
                        MessageBox.Show(json["Message"].ToString(), "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }


            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        /// <summary>
        /// 机台信息
        /// </summary>
        //private void loadMachine()
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("select cCode,cName from fun_CommonData_Info where isdel=0 ");
        //    sb.Append(" and cType in('PM','LYJT') and parentCode='3' and specFile='"+cmPars["gxCode"]+"'");
        //    var table = db.getData(sb.ToString(), "");
        //    cb_1_Machine.DataSource = table;
        //    cb_1_Machine.ValueMember = "cCode";
        //    cb_1_Machine.DisplayMember = "cName";
        //}

        private void btnClose_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            this.Close();
        }

        ///// <summary>
        ///// 已完成条码数
        ///// </summary>
        //private void DoneBarCodes()
        //{
        //    StringBuilder sb = new StringBuilder();
        //    sb.Append("select barCode,proCode,proName,spec,createtime,pusers,number,unitName");
        //    sb.Append(" from V_BarCode_Info where dataId='"+ cmPars["dataId"] +"' ");
        //    sb.Append("and baseCode='"+ CommonMethods.baseCode +"'");
        //    var table = db.getData(sb.ToString(),"");
        //    this.dvList.DataSource = table;
        //    this.dvList.AutoGenerateColumns = false;
        //    double num = 0;
        //    foreach (DataRow r in table.Rows)
        //    {
        //        num += double.Parse(r["number"].ToString());
        //    }
        //    lbMsg.Text = string.Format("已生产件数：{0}，生产数量：{1}({2})",table.Rows.Count,num,tb_0_unitName.Text);
        //    if (num >= double.Parse(tb_0_number.Text))
        //    {
        //        lbMsg.ForeColor = Color.Red;
        //    }
        //}

        private void tbMaoZhong_TextChanged(object sender, EventArgs e)
        {
            try
            {
                setNumber();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void setNumber()
        {
            if (!string.IsNullOrWhiteSpace(tbQuPi.Text) && !string.IsNullOrWhiteSpace(tbMaoZhong.Text))
            {
                tb_1_proWeight.Text = (double.Parse(tbMaoZhong.Text) - double.Parse(tbQuPi.Text)).ToString();
            }
        }

        private void tbQuPi_TextChanged(object sender, EventArgs e)
        {
            try
            {
                setNumber();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "系统提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnPauseProduction_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var plCode = tb_1_plCode.Text;

            var sql = "update pi_ProductionPlan_info set status = 'ps-pause' where plCode = '" + plCode + "' ";
            var result = db.UpdateData(sql);

            if (result == "1")
            {
                MessageBox.Show("计划已中止");
            }
            else
            {
                MessageBox.Show("计划无法中止");
            }

        }

        private void BtnFinish_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            var plCode = tb_1_plCode.Text;

            var sql = "update pi_ProductionPlan_info set status = 'ps-finish' where plCode = '" + plCode + "' ";
            var result = db.UpdateData(sql);

            if (result == "1")
            {
                MessageBox.Show("计划已完成");
            }
            else
            {
                MessageBox.Show("计划无法完成");
            }
        }

        private void tb_1_proWeight_Properties_EditValueChanged(object sender, EventArgs e)
        {
            var valLength = 0.0m;
            var valWidth = 0.0m;
            var valNetWeight = 0.0m;

            if (!string.IsNullOrEmpty(tb_1_cu_rollLength.Text))
            {
                valLength = decimal.Parse(tb_1_cu_rollLength.Text);
            }

            if (!string.IsNullOrEmpty(tb_1_cu_widthRange.Text))
            {
                valWidth = decimal.Parse(tb_1_cu_widthRange.Text);
            }

            if (!string.IsNullOrEmpty(tb_1_proWeight.Text))
            {
                valNetWeight = decimal.Parse(tb_1_proWeight.Text);
            }

            var actualSingleWeight = valLength * valWidth * valNetWeight;

            tb_0_actualSingleWeight.Text = actualSingleWeight.ToString("0.00");
        }
    }
}
